﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.IO;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Helpers;
using Eneta.Portal.Common.Definitions;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;

namespace Eneta.Portal.Literature.Pages
{
    public class LiteratureEditPage : Page
    {
        protected Repeater errorsRepeater;
        protected HtmlControl warningBox;
        protected HtmlInputHidden fromUrlField;
        protected HtmlGenericControl AdditionalErrors;

        protected const string ParameterId = "ID";

        protected Dictionary<string, string> Errors = new Dictionary<string, string>();

        private LiteratureDto _item;

        protected LiteratureDto Item
        {
            get
            {
                if (_item != null)
                    return _item;

                var idString = Request.QueryString[ParameterId];
                if (string.IsNullOrEmpty(idString))
                    return null;

                int id;
                if (!int.TryParse(idString, out id))
                    return null;

                var repository = new LiteratureRepository(SPContext.Current.Web);
                _item = repository.GetLiteratureItemById(id);
                return _item;
            }
        }

        protected bool IsAuthor
        {
            get
            {
                if (Item == null)
                    return false;
                return SPContext.Current.Web.CurrentUser.ID == Item.AuthorId;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            errorsRepeater.ItemDataBound += ErrorsRepeaterItemDataBound;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            /*if (!IsValidUser())
            {
                Response.Redirect("/");
            }*/

            warningBox.Style["display"] = "none";
        }

        #region Events

        protected void ErrorsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var label = (Label)e.Item.FindControl("errorLabel");
            label.Text = e.Item.DataItem.ToString();
        }

        #endregion

        #region Helpers

        protected bool IsValidUser()
        {
            var currentUser = SPContext.Current.Web.CurrentUser;
            if (currentUser == null)
            {
                return false;
            }

            if (Item != null)
            {
                if (string.IsNullOrEmpty(Item.Author))
                {
                    return false;
                }

                var ownerValue = new SPFieldUserValue(SPContext.Current.Web, Item.Author);
                var owner = ownerValue.User;

                if (owner == null)
                {
                    return false;
                }

                if (owner.LoginName != currentUser.LoginName)
                {
                    if (!currentUser.IsSiteAdmin)
                    {
                        return false;
                    }
                }

                if (Item.Status == SPModerationStatusType.Approved)
                {
                    if (!currentUser.IsSiteAdmin)
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        protected void SavePicture(string pageName, Guid siteId, Stream picture, string folderType)
        {

            SPSecurity.RunWithElevatedPrivileges(
                delegate
                {
                    using (var thisSite = new SPSite(siteId))
                    using (var rootWeb = thisSite.OpenWeb())
                    {
                        thisSite.AllowUnsafeUpdates = true;
                        rootWeb.AllowUnsafeUpdates = true;

                        var newImageMemoryStream = new MemoryStream();
                        var newSmallImageMemoryStream = new MemoryStream();


                        ImageHelper.ResizeImage(195, 300, picture,newImageMemoryStream);
                        ImageHelper.ResizeImage(60, 72, picture, newSmallImageMemoryStream);


                        //Create folder if missing
                        SPFolder booksFolder;
                        string folderName = string.Empty;
                        if (folderType == "Ajakiri")
                        {
                            booksFolder = rootWeb.GetFolder(Lists.Magazines.Images);
                            folderName = Lists.Magazines.Images;
                        }
                        else
                        {
                            booksFolder = rootWeb.GetFolder(Lists.Books.Images);
                            folderName = Lists.Books.Images;
                        }
                        if (!booksFolder.Exists)
                        {
                            var folder = rootWeb.GetFolder(Lists.SiteCollectionImages);
                            booksFolder = folder.SubFolders.Add(folderName);
                            folder.Update();
                        }

                        
                        var newImageFile = booksFolder.Files.Add(booksFolder.Url + "/" + pageName.Replace(".aspx", ".png"), newImageMemoryStream, true);
                        var newSmallImageFile = booksFolder.Files.Add(booksFolder.Url + "/" + pageName.Replace(".aspx", "_small.png"), newSmallImageMemoryStream, true);
                        var newImageItem = newImageFile.Item;
                        var newSmallImageItem = newSmallImageFile.Item;

                        newImageItem.Update();
                        newImageFile.Update();
                        newImageItem.ParentList.Update();

                        newSmallImageFile.Update();
                        newSmallImageItem.Update();
                        newSmallImageItem.ParentList.Update();

                        newImageMemoryStream.Dispose();
                        newSmallImageMemoryStream.Dispose();

                        thisSite.AllowUnsafeUpdates = false;
                        rootWeb.AllowUnsafeUpdates = false;
                    }
                });

        }

        protected void RenamePicture(SPWeb web, string folderName, string oldName, string newName)
        {
            SPSecurity.RunWithElevatedPrivileges(
                delegate
                {
                    using (SPSite site = new SPSite(web.Site.ID))
                    {
                        using (SPWeb currentWeb = site.OpenWeb(web.ID))
                        {
                            site.AllowUnsafeUpdates = true;
                            currentWeb.AllowUnsafeUpdates = true;
                            if (oldName.Contains(".aspx"))
                            {

                                var bookPicture = oldName.Replace(".aspx", ".png");
                                var pictureUrl = string.Format("/{0}/{1}/{2}", Lists.SiteCollectionImages, folderName ,bookPicture);
                                SPFile file = currentWeb.Site.RootWeb.GetFile(pictureUrl);
                                if (file.Exists)
                                {
                                    var newUrl = string.Format("/{0}/{1}/{2}", Lists.SiteCollectionImages, folderName, newName.Replace(".aspx", ".png"));
                                    file.MoveTo(newUrl, true);
                                    file.Update();
                                }
                                bookPicture = oldName.Replace(".aspx", "_small.png");
                                pictureUrl = string.Format("/{0}/{1}/{2}", Lists.SiteCollectionImages, folderName, bookPicture);
                                file = currentWeb.Site.RootWeb.GetFile(pictureUrl);
                                if (file.Exists)
                                {
                                    var newUrl = string.Format("/{0}/{1}/{2}", Lists.SiteCollectionImages, folderName, newName.Replace(".aspx", "_small.png"));
                                    file.MoveTo(newUrl, true);
                                    file.Update();
                                }
                            }
                            else
                            {
                                Logger.LogInfo("Current page name is not valid", "LiteratureEditPage_RenamePicture");
                            }
                            site.AllowUnsafeUpdates = false;
                            currentWeb.AllowUnsafeUpdates = false;
                        }
                    }
                });
        }

        protected void ApplyErrors(Dictionary<string, string> errors)
        {
            if (errors.Count == 0)
            {
                AdditionalErrors.Visible = false;
                return;
            }

            var unboundErrors = new List<string>();

            foreach (string fieldKey in errors.Keys)
            {
                var error = errors[fieldKey];
                var ctl = (HtmlGenericControl)this.FindControl(fieldKey + "Container", true);
                if (ctl == null)
                {
                    unboundErrors.Add(error);
                    continue;
                    //Response.End();
                }
                ctl.Attributes.Add("class", "info-row failed-info");
                ctl = (HtmlGenericControl)this.FindControl(fieldKey + "ErrorMessage", true);
                if (ctl == null)
                {
                    Response.Write("Ei leia konteinerit: " + fieldKey + "ErrorMessage<br>");
                    Response.End();
                }
                else
                    ctl.Style["display"] = "";

                ctl = (HtmlGenericControl)this.FindControl(fieldKey + "ErrorLabel", true);
                if (ctl == null)
                {
                    Response.Write("Ei leia konteinerit: " + fieldKey + "ErrorLabel<br>");
                    Response.End();
                }
                else
                    ctl.InnerText = error;
            }
            foreach (var err in unboundErrors)
                Logger.LogInfo("ApplyErrors: Unbound error: " + err, GetType().ToString());
            errorsRepeater.DataSource = unboundErrors;
            errorsRepeater.DataBind();
            Logger.LogInfo("ApplyErrors: Display", GetType().ToString());
            warningBox.Style["display"] = "";
        }

        #endregion
    }
}
